package com.yuzhi.master.sewage.device.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuzhi.common.core.domain.entity.SysDictData;
import com.yuzhi.common.util.StringUtils;
import com.yuzhi.master.pump.mapper.DrainPumpMapper;
import com.yuzhi.master.pump.mapper.DrainRRmstMapper;
import com.yuzhi.master.sewage.device.domain.DrainDevice;
import com.yuzhi.master.sewage.device.domain.bo.DrainDeviceBo;
import com.yuzhi.master.sewage.device.domain.request.DrainDeviceReq;
import com.yuzhi.master.sewage.device.domain.vo.DrainDeviceVo;
import com.yuzhi.master.sewage.device.mapper.DrainDeviceMapper;
import com.yuzhi.master.sewage.device.service.IDrainDeviceService;
import com.yuzhi.master.sewage.pipe.mapper.DrainPipeMapper;
import com.yuzhi.master.sewage.wmst.mapper.DrainWmstMapper;
import com.yuzhi.master.sewageTreatment.mapper.SewageTreatmentMapper;
import com.yuzhi.master.sewageTreatment.service.SewageTreatmentService;
import com.yuzhi.system.service.ISysDictTypeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 排水设备表 服务类
 */
@RequiredArgsConstructor
@Service
public class DrainDeviceServiceImpl extends ServiceImpl<DrainDeviceMapper, DrainDevice> implements IDrainDeviceService {

    private final DrainDeviceMapper drainDeviceMapper;

    private final ISysDictTypeService iSysDictTypeService;

    private final DrainRRmstMapper drainRRmstMapper;

    private final SewageTreatmentMapper sewageTreatmentMapper;

    private final DrainPumpMapper drainPumpMapper;

    private final DrainPipeMapper drainPipeMapper;

    private final DrainWmstMapper drainWmstMapper;


    private final SewageTreatmentService sewageTreatmentService;



    private LambdaQueryWrapper<DrainDevice> buildQueryWrapper(DrainDeviceReq request) {
        Map<String, Object> params = request.getParams();
        LambdaQueryWrapper<DrainDevice> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(request.getDeviceId()), DrainDevice::getDeviceId, request.getDeviceId());
        lqw.eq(StringUtils.isNotBlank(request.getFacilityId()), DrainDevice::getFacilityId, request.getFacilityId());
        lqw.eq(request.getDeviceType() != null, DrainDevice::getDeviceType, request.getDeviceType());
        //1：污水厂、2：泵站、3：排水管网
        lqw.eq(request.getFacilityType() != null, DrainDevice::getFacilityType, request.getFacilityType());
        // 运行状态
        lqw.eq(request.getSyzt() != null, DrainDevice::getSyzt, request.getSyzt());
        lqw.orderByDesc(DrainDevice::getUpdateTime);
        return lqw;
    }

    /**
     * 新增排水设备信息
     */
    @Override
    public Boolean insertByBo(DrainDeviceBo bo) {
        DrainDevice add = BeanUtil.toBean(bo, DrainDevice.class);
        validEntityBeforeSave(add);
        boolean flag = drainDeviceMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改管道信息
     */
    @Override
    public Boolean updateByBo(DrainDeviceBo bo) {
        DrainDevice update = BeanUtil.toBean(bo, DrainDevice.class);
        validEntityBeforeSave(update);
        return drainDeviceMapper.updateById(update) > 0;
    }

    /**
     * 批量删除排水设备信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            // 业务校验逻辑
        }
        return drainDeviceMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 根据id删除管道信息
     */
    @Override
    public Boolean deleteById(String id, Boolean isValid) {
        if (isValid) {
            // 业务校验逻辑
        }
        return drainDeviceMapper.deleteById(id) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DrainDevice entity) {
        // 可添加唯一约束校验等业务逻辑
    }

    /**
     * 将数据字典值转换为MAP
     *
     * @param queryType
     * @return
     */
    private Map<Integer, String> chanegMapByList(String queryType) {

        List<SysDictData> dictDataList = iSysDictTypeService.selectDictDataByType(queryType);

        Map<Integer, String> newMap = dictDataList.stream()
                .filter(data -> data.getDictValue() != null) // 过滤null值
                .filter(data -> {
                    try {
                        Integer.parseInt(data.getDictValue());
                        return true;
                    } catch (NumberFormatException e) {
                        return false; // 忽略无法转换为Integer的字符串
                    }
                })
                .collect(Collectors.toMap(
                        data -> Integer.parseInt(data.getDictValue()), // 将String转为Integer作为Key
                        data -> data.getDictLabel() != null ? data.getDictLabel() : "", // 处理null的dictLabel
                        (existing, replacement) -> existing // 键冲突时保留现有值
                ));

        return newMap;
    }


    /**
     * 导出排水设备
     * @param request
     * @return
     */
    @Override
    public List<DrainDeviceVo> queryList(DrainDeviceReq request)
    {
        LambdaQueryWrapper<DrainDevice> lqw = buildQueryWrapper(request);

        List<DrainDeviceVo> list  = drainDeviceMapper.selectVoList(lqw);


        //设备类型 device_type
        Map<Integer, String> deviceTypeMap = chanegMapByList("device_type");
        list.stream()
                .peek(device -> {
                    Integer stateCode = device.getDeviceType();
                    device.setDeviceTypeStr(deviceTypeMap.getOrDefault(stateCode, "未知设备类型"));
                })
                .collect(Collectors.toList());

        //排水设备使用状态  device_syzt_status
        Map<Integer, String> deviceSyztStatusMap = chanegMapByList("device_syzt_status");
        list.stream()
                .peek(device -> {
                    Integer stateCode = device.getSyzt();
                    device.setSyztStr(deviceSyztStatusMap.getOrDefault(stateCode, "未知状态"));
                })
                .collect(Collectors.toList());

        //排水设备维护周期  device_whzq_type
        Map<Integer, String> deviceWhzqMap = chanegMapByList("device_whzq_type");
        list.stream()
                .peek(device -> {
                    Integer stateCode = device.getWhzq();
                    device.setWhzqStr(deviceWhzqMap.getOrDefault(stateCode, "未知维护周期"));
                })
                .collect(Collectors.toList());

        return list;
    }
}
